package com.lcp.se.server;

import com.alibaba.fastjson.JSON;
import com.lcp.se.config.ServerInfoConfig;
import com.lcp.se.service.AmqpMessageService;
import com.lcp.se.util.Result;
import com.lcp.se.util.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 1 对 1 即时通讯
 *
 * @author lcp
 * @since 2020/7/18 22:19
 */

@ServerEndpoint("/im/{userOpenId}/{userType}")
@Component
public class ImServer {
    private final Logger log = LoggerFactory.getLogger(AmqpMessageService.class);
    /**
     * 使用map对象，便于根据userOpenId来获取对应的WebSocket
     */
    private static final ConcurrentHashMap<String, ImServer> WEBSOCKET_LIST = new ConcurrentHashMap<>();

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * 静态变量 staticRedisTemplate，结合下面的 @PostConstruct 进行值注入
     */
    private static RedisTemplate<String, String> staticRedisTemplate;

    private static String staticSocketInfoKey;
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 存放 userOpenId
     */
    private String userOpenId = "";
    /**
     * 存放 userType
     */
    private Integer userType;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${mini-program.socket-info-key-redis}")
    private String socketInfoKey;

    public static synchronized void addOnlineCount() {
        ImServer.onlineCount++;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void subOnlineCount() {
        ImServer.onlineCount--;
    }

    @PostConstruct
    public void init() {
        // 取巧注入静态变量，不然下面使用 redisTemplate 会始终为 null
        staticRedisTemplate = redisTemplate;
        staticSocketInfoKey = socketInfoKey;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userOpenId") String userOpenId,
                       @PathParam("userType") Integer userType) {
        // 移除旧的连接
        try {
            ImServer socket = WEBSOCKET_LIST.get(userOpenId);
            if (socket != null) {
                log.info("重复登陆");
                socket.sendMessage(JSON.toJSONString(
                        new Result<>(false, StatusCode.REPEAT_LOGIN_ERROR, "您已在别处登录，强制下线")));
                // 关闭连接，会自动触发 onclose 方法
                socket.session.close(
                        new CloseReason(CloseReason.CloseCodes.getCloseCode(1013), "repeat login"));
                WEBSOCKET_LIST.remove(socket.userOpenId);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.session = session;
        this.userType = userType;
        this.userOpenId = userOpenId;
        WEBSOCKET_LIST.put(userOpenId, this);
        staticRedisTemplate.opsForHash().put(staticSocketInfoKey, this.userOpenId, ServerInfoConfig.serverInfo);
        addOnlineCount();
        log.info("有新的用户：" + userOpenId + " 用户类型：" + userType + "，当前在线人数为"
                + getOnlineCount() + "\twebsocketList" + ".size：" + WEBSOCKET_LIST.size());
        this.sendMessage(JSON.toJSONString(new Result<>(true, StatusCode.OK, "连接成功")));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (WEBSOCKET_LIST.get(this.userOpenId) != null) {
            WEBSOCKET_LIST.remove(this.userOpenId);
            staticRedisTemplate.opsForHash().delete(staticSocketInfoKey, this.userOpenId);
            subOnlineCount();
            // log.info("有一连接关闭！当前在线人数为：" + getOnlineCount());
            log.info("有一连接关闭！当前在线人数为：" + WEBSOCKET_LIST.size());
        }
    }

    /**
     * 连接出错
     *
     * @param error 发生的错误
     */
    @OnError
    public void onError(Throwable error) {
        log.error("发生错误：" + error.getMessage());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        if (message.equals("ping")) {
            this.sendMessage("pong");
            return;
        }
        log.info("收到来自窗口" + userOpenId + "的信息:" + message);
    }

    /**
     * 发送消息的方法
     */
    public void sendMessage(String message) {
        this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 发送消息给指定的人
     */
    public void sendToOne(String message, String toUserOpenId) {
        ImServer socket = WEBSOCKET_LIST.get(toUserOpenId);
        if (socket != null) {
            socket.sendMessage(message);
        }
    }
}
